/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package luft27.comm;

import com.engidea.comm.CommPortIdentifier;
import com.engidea.comm.SerialPort;
import com.engidea.win32jcom.WinjcomIdentifier;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author amalikov
 */
public class COMStream implements SerialStream {

	public COMStream(String portName, int baudRate, int timeout) {
		super();
		this.portName = "\\\\.\\" + portName;
		this.baudRate = baudRate;
		this.timeout = timeout;
		portIdentifier = new WinjcomIdentifier(0);
		opened = false;
	}

	private void open() throws IOException {
		if (opened)
			return;

		comPort = (SerialPort) portIdentifier.getCommPort(portName);
		comPort.close();
		comPort.open();

		comPort.setSerialPortParams(
				baudRate,
				SerialPort.DATABITS_8,
				SerialPort.STOPBITS_1,
				SerialPort.PARITY_NONE);

		comPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
		comPort.enableReceiveTimeout(timeout);

		opened = true;
	}

	@Override
	public void close() {
		if (comPort != null)
			comPort.close();
		opened = false;
	}

	@Override
	public int read(byte[] data, int ofs, int len) {
		try {
			open();
			int res = comPort.read(data, ofs, len);
			return (res > 0) ? res : 0;
		} catch (IOException ex) {
			Logger.getLogger(COMStream.class.getName()).log(Level.SEVERE, null, ex);
			return 0;
		}
	}

	@Override
	public int read() {
		byte[] a = new byte[1];
		int res = read(a, 0, 1);
		return (res > 0) ? a[0] : -1;
	}

	@Override
	public void write(byte[] data, int ofs, int len) {
		try {
			open();
			comPort.write(data, ofs, len);
		} catch (IOException ex) {
			Logger.getLogger(COMStream.class.getName()).log(Level.SEVERE, null, ex);
		}
	}

	@Override
	public void clean() {
		try {
			open();
			comPort.flush();
		} catch (IOException ex) {
			Logger.getLogger(COMStream.class.getName()).log(Level.SEVERE, null, ex);
		}
	}
	private final String portName;
	private final int baudRate;
	private final int timeout;
	private boolean opened;
	private CommPortIdentifier portIdentifier;
	private SerialPort comPort;
}
